# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.
class ApplicationController < ActionController::Base
  helper :all # include all helpers, all the time

  before_filter :set_user
  
protected  
  def set_user
    begin
      @user = User.find(session[:id])
    rescue ActiveRecord::RecordNotFound
      return nil;
    end
  end
  
  def login_required # use if a page/action needs user to be logged in (any user)
    return true if @user
    access_denied
    return false
  end
  
  def user_required
    if @user
      if !@user.is_disabled
        return true
      end
      access_denied
      return false
    end
    access_denied
    return false
  end

  def editor_required
    if @user       
      if @user.is_editor && !@user.is_disabled
        return true
      end
      editor_denied
      return false
    end
    editor_denied
    return false
  end
  
  def admin_required # use if a page/action requires an admin to be logged in.
    if @user
      if @user.is_admin && !@user.is_disabled
        return true
      end
      admin_denied  
      return false
    end
    admin_denied
    return false
  end
  
  def access_denied
    session[:return_to] = request.request_uri
    flash[:error] = "You must login to view this page"
    redirect_to :controller => 'user', :action => 'login'
  end
  
  def editor_denied
    session[:return_to] = request.request_uri
    flash[:error] = "You must login as an editor to view this page"
    redirect_to :controller => 'user', :action => 'login'
  end
  
  def admin_denied
    session[:return_to] = request.request_uri
    flash[:error] = "You must login as an admin to view this page"
    redirect_to :controller => 'user', :action => 'login'
  end
  
  def user_disabled
    redirect_to :controler => 'user', :action => 'disabled'
  end

  # See ActionController::RequestForgeryProtection for details
  # Uncomment the :secret if you're not using the cookie session store
  protect_from_forgery # :secret => '5fb5b1a1cf2e1876df2a4f1915034b11'
  
  
end
